package svc

import (
	"github.com/hibiken/asynq"
	"github.com/spf13/viper"
)

type FileBasedConfigProvider struct {
	filename string
}

func NewFileBaseConfigProvider(filename string) *FileBasedConfigProvider {
	return &FileBasedConfigProvider{
		filename: filename,
	}
}

type Task struct {
	Cronspec string
	TaskType string
	Payload  string
}

type AllConfig struct {
	Schedules []*Task
}

var allConf = &AllConfig{}

func (p *FileBasedConfigProvider) GetConfigs() ([]*asynq.PeriodicTaskConfig, error) {

	viper.SetConfigFile(p.filename)
	// viper.SetConfigType("yaml")
	err := viper.ReadInConfig()
	if err != nil {
		return nil, err
	}
	if err := viper.Unmarshal(allConf); err != nil {
		return nil, err
	}

	var configs []*asynq.PeriodicTaskConfig
	for _, cfg := range allConf.Schedules {
		var payload []byte
		if len(cfg.Payload) > 0 {
			payload = []byte(cfg.Payload)
		}
		configs = append(configs, &asynq.PeriodicTaskConfig{Cronspec: cfg.Cronspec, Task: asynq.NewTask(cfg.TaskType, payload)})
	}
	return configs, nil
}
